package com.uenpay.im.panel;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qiyunxin.android.http.listener.OnMediaRecoderListener;
import com.qiyunxin.android.http.media.Recorder;
import com.qiyunxin.android.http.view.ResizeLayout;
import com.qyx.android.weight.edittext.Emoji;
import com.qyx.android.weight.view.SliderDirectViewPager;
import com.qyx.android.weight.view.SliderDirectViewPager.MyDirectListener;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.publicnumber.PublicNumMenu;
import com.uenpay.im.ui.old.activity.stickers.StickerActivity;
import com.uenpay.im.panel.emoji.EmojiAdapter;
import com.uenpay.im.panel.emoji.OnEmojiSelected;
import com.uenpay.im.panel.emoji.QyxEmoji;
import com.uenpay.im.panel.emojitype.BottomEmojiAdapter;
import com.uenpay.im.panel.emojitype.CheckEmojiEntity;
import com.uenpay.im.panel.gif.GifAdapter;
import com.uenpay.im.panel.gif.OnBuildInViewGifSelected;
import com.uenpay.im.panel.gif.ViewGifCover;
import com.uenpay.im.panel.more.IMoreOnClickListener;
import com.uenpay.im.panel.more.MoreEntity;

import java.util.ArrayList;

/**
 * @author SL
 * @created 2016-4-12 下午3:42:51
 * @copyRight http://www.qiyunxin.com
 * @function 面板管理
 */
public class FacePanelManager {

	/**
	 * 是否在录音标识.default：false
	 */
	private boolean recording = false;
	private boolean isInside = false;
	/**
	 * 录音的开始时间
	 */
	private long recordStartTime;
	/**
	 * 结束录音时间
	 */
	private long recordEndTime;
	/**
	 * 录音时间差
	 */
	private long timeTrad;
	private Rect rect;
	/**
	 * 更新录音动画的hanler
	 */
	private Handler volumeHandler = new Handler();
	private Handler recordHandler = new Handler();
	/**
	 * 语音动画图片
	 */
	private ImageView audioRecordVolume;
	/**
	 * 语音处理 动画总布局
	 */
	private RelativeLayout recodeAudioLogView;
	/**
	 * 计算软键盘高度
	 */
	private ResizeLayout mResizeLayout;
	private ViewPager moreViewPager;
	private SliderDirectViewPager gifViewPager;
	private RecyclerView listView;
	private BottomEmojiAdapter mBottomEmojiAdapter;
	private LinearLayout indexGroup, moreIndexGroup;
	private GifAdapter mAdapter = null;
	private EmojiAdapter emojiAdapter = null;
	private CheckEmojiEntity selectedCheckEmoji = null;
	private ArrayList<CheckEmojiEntity> arrayList = null;
	private int keyboardHeight = 0;
	/***
	 * 底部布局
	 */
	private View action_view, recordView;
	private InputMethodManager inputManager;
	private EditText sendEdit;
	/**
	 * emojiBtn:表情按钮 ,addMoreBtn:更多按钮,audioBtn:语音按钮,publicNumSoft:公众号按钮
	 */
	private ImageView emojiBtn, addMoreBtn, audioBtn, publicNumSoft;
	/**
	 * 发送消息按钮
	 */
	private TextView send;
	/**
	 * 发送语音按钮
	 */
	private Button sendAudioButton;
	/**
	 *
	 */
	private LinearLayout editView;
	/**
	 * 更多布局
	 */
	private LinearLayout more_actions, emoji_action;
	private LinearLayout emoji_add_layout, emoji_setting_layout;
	/**
	 * 公众号textview
	 */
	private TextView publicNumMenuTv1, publicNumMenuTv2, publicNumMenuTv3;
	private View public_num_view;
	/**
	 * 公众号布局和输入框布局
	 */
	private LinearLayout publicNumLayout, kayboadFrameLayout;

	private PanelManagerInterface.ISendAudioListener mSendAudioListener = null;
	private PanelManagerInterface.ISendTextListener mSendTextListener = null;
	private PanelManagerInterface.ISendGifListener mISendGifListener = null;
	private PanelManagerInterface.IScrollToEnd mIScrollToEnd = null;
	private PanelManagerInterface.IInputSpecialChar mIInputSpecialChar = null;
	private Context mContext;
	private PanelMoreManager mPanelMoreManager;
	private PanelPublicNumManager mPanelPublicNumManager;
	private boolean isShowPublicNumSoft = false;

	/**
	 * 面板管理
	 *
	 * @param _Context
	 * @param view
	 *            面板布局
	 * @param _recordView
	 *            录音布局
	 * @param _ResizeLayout
	 *            获取软键盘高度
	 * @param is_show_public_num_soft
	 *            是否显示公众号软键盘
	 */
	public FacePanelManager(Context _Context, View view, View _recordView,
			ResizeLayout _ResizeLayout, boolean is_show_public_num_soft) {
		isShowPublicNumSoft = is_show_public_num_soft;
		mResizeLayout = _ResizeLayout;
		mContext = _Context;
		recordView = _recordView;
		initView(view);
		mPanelMoreManager = new PanelMoreManager(moreIndexGroup, moreViewPager,
				mContext);
		mPanelPublicNumManager = new PanelPublicNumManager(_Context,
				kayboadFrameLayout, publicNumLayout, publicNumSoft,
				public_num_view, publicNumMenuTv1, publicNumMenuTv2,
				publicNumMenuTv3);
	}

	// 初始化控件
	private void initView(View view) {
		inputManager = (InputMethodManager) mContext
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		emojiBtn = (ImageView) view.findViewById(R.id.action_show_emoji_panel);
		emoji_add_layout = (LinearLayout) view
				.findViewById(R.id.emoji_add_layout);
		emoji_setting_layout = (LinearLayout) view
				.findViewById(R.id.emoji_setting_layout);
		action_view = view.findViewById(R.id.action_view);
		addMoreBtn = (ImageView) view.findViewById(R.id.addMoreBtn);
		audioBtn = (ImageView) view.findViewById(R.id.audio_switch_btn);

		gifViewPager = (SliderDirectViewPager) view.findViewById(R.id.gif_list);
		moreViewPager = (ViewPager) view.findViewById(R.id.more_list_viewpager);
		indexGroup = (LinearLayout) view.findViewById(R.id.points_view);
		moreIndexGroup = (LinearLayout) view
				.findViewById(R.id.more_points_view);
		mResizeLayout.setOnResizeListener(resizeListener);
		sendEdit = (EditText) view.findViewById(R.id.editText);
		send = (TextView) view.findViewById(R.id.send_btn);
		more_actions = (LinearLayout) view.findViewById(R.id.more_actions);
		emoji_action = (LinearLayout) view.findViewById(R.id.emoji_action);
		editView = (LinearLayout) view.findViewById(R.id.edit_view);
		sendAudioButton = (Button) view.findViewById(R.id.sendAudio);
		recodeAudioLogView = (RelativeLayout) recordView
				.findViewById(R.id.recode_view);
		recodeAudioLogView.setVisibility(View.GONE);
		audioRecordVolume = (ImageView) recordView
				.findViewById(R.id.audio_record_volume);

		/**
		 * 公众号
		 */
		publicNumSoft = (ImageView) view.findViewById(R.id.public_num_soft);
		publicNumMenuTv1 = (TextView) view.findViewById(R.id.publicNumMenuTv1);
		publicNumMenuTv2 = (TextView) view.findViewById(R.id.publicNumMenuTv2);
		publicNumMenuTv3 = (TextView) view.findViewById(R.id.publicNumMenuTv3);

		publicNumLayout = (LinearLayout) view
				.findViewById(R.id.publicNumLayout);
		kayboadFrameLayout = (LinearLayout) view
				.findViewById(R.id.kayboadFrame);
		public_num_view = view.findViewById(R.id.public_num_view);
		sendEdit.setFocusable(true);
		sendEdit.setFocusableInTouchMode(true);
		sendEdit.requestFocus();
		initHorizaontal(view);
		int tempHeight = IMApplication.config.getKeyBoardHeight();
		if (tempHeight != 0) {
			keyboardHeight = tempHeight;
			setFaceActionViewHeight();
		}
	}

	public void initListener() {
		emojiBtn.setOnClickListener(clickListener);
		addMoreBtn.setOnClickListener(clickListener);
		emoji_add_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				IMApplication.showToast("添加更多表情");
			}
		});
		emoji_setting_layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				IMApplication.showToast("表情设置");
			}
		});
		/** 内容编辑框事件 **/
		sendEdit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mIScrollToEnd != null) {
					mIScrollToEnd.onScrollToEnd();
				}
				showSoftKeyboard();
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				sendEdit.setFocusable(true);
				sendEdit.setFocusableInTouchMode(true);
				sendEdit.requestFocus();
				setActionViewDisplay(1);
				emojiBtn.setImageResource(R.drawable.emoji);
			}
		});
		sendEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (TextUtils.isEmpty(s)
						|| TextUtils.isEmpty(sendEdit.getText().toString()
								.trim())) {
					send.setVisibility(View.GONE);
					addMoreBtn.setVisibility(View.VISIBLE);
					return;
				}
				if (count <= 0) {
					return;
				}

				/** 控制发送按钮和更多按钮的显示和隐藏 **/
				if (sendEdit.getText().toString().trim().length() > 0) {
					send.setVisibility(View.VISIBLE);
					addMoreBtn.setVisibility(View.GONE);
				} else {
					send.setVisibility(View.GONE);
					addMoreBtn.setVisibility(View.VISIBLE);
				}
				char c = s.charAt(s.length() - 1);
				String str = String.valueOf(c);
				/** 如果是输入的@（显示群里面的群员） **/
				if (str.equals("@")) {
					if (mIInputSpecialChar != null) {
						mIInputSpecialChar.onInputSpecialChar();
					}
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String content = sendEdit.getText().toString();
				if (mSendTextListener != null) {
					mSendTextListener.onSendTextContent(content);
				}
				sendEdit.setText("");
			}
		});

		/********* 语音按钮操作 ************/
		audioBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				/** 隐藏编辑框、显示发送语音按钮 **/
				if (sendAudioButton.getVisibility() == View.GONE) {
					editView.setVisibility(View.GONE);
					sendAudioButton.setVisibility(View.VISIBLE);
					audioBtn.setImageResource(R.drawable.talk_detail_keyboard_btn);
					hideSoftKeyboard();
					// actionView.setVisibility(View.GONE);
					setActionViewDisplay(1);
				} else {
					/** 显示编辑框、隐藏发送语音按钮 **/
					editView.setVisibility(View.VISIBLE);
					sendAudioButton.setVisibility(View.GONE);
//					emojiBtn.setImageResource(R.drawable.emoji);
					audioBtn.setImageResource(R.drawable.talk_detail_audio_btn);
					sendEdit.setFocusable(true);
					sendEdit.setFocusableInTouchMode(true);
					sendEdit.requestFocus();
					showSoftKeyboard();
				}
//				emojiBtn.setBackgroundResource(R.drawable.emoji);
			}
		});

		/** 发送语音按钮 **/
		sendAudioButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(final View view, MotionEvent motionEvent) {

				if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
					QyxAudioManage.deleteCacheLog(QyxAudioManage
							.getRecorderPath());
					rect = new Rect(view.getLeft(), view.getTop(), view
							.getRight(), view.getBottom());
					sendAudioButton
							.setBackgroundResource(R.drawable.button_audio_bg);

					volumeHandler.removeCallbacks(volume_runable);
					recordHandler.removeCallbacks(record_runable);
					recordHandler.postDelayed(record_runable, 200);

				} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
					if (recodeAudioLogView.getVisibility() == View.VISIBLE) {
						if (!rect.contains(
								view.getLeft() + (int) motionEvent.getX(),
								view.getTop() + (int) motionEvent.getY())) {
							isInside = false;
							if (recordListener != null) {
								recordListener.onMoving(isInside);
							}
							recodeAudioLogView.findViewById(R.id.out_view)
									.setVisibility(View.VISIBLE);
							recodeAudioLogView.findViewById(R.id.in_view)
									.setVisibility(View.GONE);
							sendAudioButton
									.setBackgroundResource(R.drawable.button_audio_bg);
						} else {
							isInside = true;
							if (recordListener != null) {
								recordListener.onMoving(isInside);
							}
							recodeAudioLogView.findViewById(R.id.out_view)
									.setVisibility(View.GONE);
							recodeAudioLogView.findViewById(R.id.in_view)
									.setVisibility(View.VISIBLE);
							sendAudioButton
									.setBackgroundResource(R.drawable.button_audio_bg);
						}
					}
				} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
					volumeHandler.removeCallbacks(volume_runable);
					recordHandler.removeCallbacks(record_runable);
					sendAudioButton.setEnabled(false);
					sendAudioButton
							.setBackgroundResource(R.drawable.button_audio_bg);
					if (recording) {
						// TODO 发送语音
						sendAudio(QyxAudioManage.getRecorderPath());
					} else {
						sendAudioButton.setEnabled(true);
					}
				}
				return false;
			}
		});

		/** 公众号和标签输入框切换 **/
		publicNumSoft.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (kayboadFrameLayout.getVisibility() == View.VISIBLE) {
					// TODO
					kayboadFrameLayout.setVisibility(View.GONE);
					publicNumLayout.setVisibility(View.VISIBLE);
					publicNumSoft.setImageResource(R.drawable.icon_menu_top);
				} else {
					kayboadFrameLayout.setVisibility(View.VISIBLE);
					publicNumLayout.setVisibility(View.GONE);
					publicNumSoft.setImageResource(R.drawable.icon_menu_bottom);
				}
				sendEdit.setFocusable(true);
				sendEdit.setFocusableInTouchMode(true);
				sendEdit.requestFocus();
//				emojiBtn.setBackgroundResource(R.drawable.emoji);
				setActionViewDisplay(1);
				inputManager.hideSoftInputFromWindow(sendEdit.getWindowToken(),
						0);
			}
		});

		if (isShowPublicNumSoft) {
			publicNumSoft.setVisibility(View.VISIBLE);
			publicNumLayout.setVisibility(View.VISIBLE);
		}
	}

	private void initHorizaontal(View view) {
		listView = (RecyclerView) view
				.findViewById(R.id.recyclerview_horizontal);
		// 创建一个线性布局管理器
		LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
		layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
		// 设置布局管理器
		listView.setLayoutManager(layoutManager);
		getData();
	}

	private void getData() {
		arrayList = new ArrayList<CheckEmojiEntity>();
		CheckEmojiEntity mCheckEmojiEntity1 = new CheckEmojiEntity(1,
				R.drawable.ajmd_s_pressed, "yutumei");
		CheckEmojiEntity mCheckEmojiEntity2 = new CheckEmojiEntity(2,
				R.drawable.icon_favorite, "like");

		// CheckEmojiEntity mCheckEmojiEntity1 = new CheckEmojiEntity(1,
		// R.drawable.ajmd_s_pressed, "ajmd");
		// CheckEmojiEntity mCheckEmojiEntity2 = new CheckEmojiEntity(2,
		// R.drawable.lt_s_pressed, "lt");
		// CheckEmojiEntity mCheckEmojiEntity3 = new CheckEmojiEntity(3,
		// R.drawable.xxy_s_pressed, "xxy");
		// CheckEmojiEntity mCheckEmojiEntity4 = new CheckEmojiEntity(4,
		// R.drawable.xxy_s_pressed, "xxy");
		arrayList.add(mCheckEmojiEntity2);
		arrayList.add(mCheckEmojiEntity1);

		// msg_list.add(mCheckEmojiEntity2);
		// msg_list.add(mCheckEmojiEntity3);
		// msg_list.add(mCheckEmojiEntity4);
		// 设置emoji表情在第一个
		arrayList.add(0, new CheckEmojiEntity(-1, -1, ""));
		mBottomEmojiAdapter = new BottomEmojiAdapter(mContext, arrayList,
				new BottomEmojiAdapter.IOnItemClick() {

					@Override
					public void onItemClick(CheckEmojiEntity mCheckEmojiEntity) {
						if (mCheckEmojiEntity != null) {
							if (selectedCheckEmoji == mCheckEmojiEntity) {
								return;
							} else {
								selectedCheckEmoji = mCheckEmojiEntity;
							}
							mBottomEmojiAdapter
									.setSelectedItem(mCheckEmojiEntity.id);
							if (mCheckEmojiEntity.id == -1
									&& mCheckEmojiEntity.resourceId == -1
									&& TextUtils
											.isEmpty(mCheckEmojiEntity.resourceName)) {
								showIndexMark(0, 1,
										mCheckEmojiEntity.resourceName);
							} else {
								showIndexMark(0, 2,
										mCheckEmojiEntity.resourceName);
							}
						}
					}
				});
		listView.setAdapter(mBottomEmojiAdapter);
		// 设置默认值
		showIndexMark(0, 1, "");
		selectedCheckEmoji = arrayList.get(0);
		mBottomEmojiAdapter.setSelectedItem(selectedCheckEmoji.id);
	}

	/**
	 * 语音动画
	 */
	private Runnable volume_runable = new Runnable() {
		@Override
		public void run() {
			if (recording) {
				int i = Recorder.getInstance().GetVisualizer();
				//录音动画回调接口
				if (recordListener != null) {
					recordListener.onRecording(QyxAudioManage.getCurrentSeconds() - recordStartTime);
				}
				if (i != 0) {
					i = i / 5000;
					i = i > 4 ? 4 : i;
					audioRecordVolume
							.setImageResource(QyxAudioManage.audioRecordVolumeResource[i]);
				}
			}
			volumeHandler.postDelayed(this, 200);
		}
	};

	private Runnable record_runable = new Runnable() {

		@Override
		public void run() {

			Recorder.getInstance()
					.SetOnMediaRecoderListener(new OnMediaRecoderListener() {

						@Override
						public void onOverMaxFileSize(int maxFileSizeBytes) {
						}

						@Override
						public void onOverDuration(int maxTimeMills) {
							// method stub
							if (recording) {
								// timer.cancel();
								// IMApplication.showToast(getResources()
								// .getString(
								// R.string.over_record_duration));
								sendAudioButton
										.setBackgroundResource(R.drawable.button_audio_bg);
								// TODO 发送语音
								sendAudio(QyxAudioManage.getRecorderPath());
							}
						}

						@Override
						public void onFail(String reason) {
							if (recording) {
								sendAudioButton
										.setBackgroundResource(R.drawable.button_audio_bg);
								isInside = false;
								if (recordListener != null) {
									recordListener.onFailed();
								}
								// TODO 发送语音
								sendAudio("");
							}
						}

						@Override
						public void onStart() {
							recodeAudioLogView.setVisibility(View.VISIBLE);
							recodeAudioLogView.findViewById(R.id.out_view)
									.setVisibility(View.GONE);
							recodeAudioLogView.findViewById(R.id.in_view)
									.setVisibility(View.VISIBLE);
							volumeHandler.postDelayed(volume_runable, 200);
							recording = true;
							isInside = true;

							recordStartTime = QyxAudioManage
									.getCurrentSeconds();
							if (recordListener != null) {
								recordListener.onStart();
							}

						}
					}).Start(QyxAudioManage.getRecorderPath(), 60000, 0);

		}
	};

	public interface IRecordListener{
		void onStart();
		void onFailed();
		void onRecording(long seconds);
		void onFinished();
		void onMoving(boolean inSide);
	}
	private IRecordListener recordListener;

	public void addOnRecordListener(IRecordListener listener) {
		recordListener = listener;
	}

	private void sendAudio(String recorderPath) {
		if (recordListener != null) {
			recordListener.onFinished();
		}
		volumeHandler.removeCallbacks(volume_runable);
		recordHandler.removeCallbacks(record_runable);
		recordEndTime = QyxAudioManage.getCurrentSeconds();
		timeTrad = recordEndTime - recordStartTime;
		recodeAudioLogView.setVisibility(View.GONE);
		Recorder.getInstance().Stop();
		recording = false;
		if (isInside) {
			if (timeTrad <= 1) {
				// IMApplication.showToast(getResources().getString(
				// R.string.record_too_short));
				sendAudioButton.setEnabled(true);
			} else {
				// TODO 回调给Activity处理
				Log.e("语音地址", "" + recorderPath);
				sendAudioButton.setEnabled(true);
				// sendRecordAudio(recorderPath);
				if (mSendAudioListener != null) {
					mSendAudioListener
							.onSendAudio((int) timeTrad, recorderPath);
				}
			}
		} else {
			sendAudioButton.setEnabled(true);
		}
		isInside = false;
	}

	/**
	 * 表情按钮和更多按钮点击事件
	 */
	private final OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (mIScrollToEnd != null) {
				mIScrollToEnd.onScrollToEnd();
			}
			gifViewPager.setVisibility(View.VISIBLE);
			sendEdit.setFocusable(true);
			sendEdit.setFocusableInTouchMode(true);
			sendEdit.requestFocus();
			if (v == emojiBtn) {
				if (action_view.getVisibility() == View.VISIBLE) {
					if (more_actions.getVisibility() == View.VISIBLE) {
						more_actions.setVisibility(View.GONE);
						emoji_action.setVisibility(View.VISIBLE);
						emojiBtn.setImageResource(R.drawable.ic_emoji_selector);
						return;
					}
					showSoftKeyboard();
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					setActionViewDisplay(1);
					emojiBtn.setBackgroundResource(R.drawable.emoji);
				} else {
					hideSoftKeyboard();
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					setActionViewDisplay(2);
					emoji_action.setVisibility(View.VISIBLE);
					emojiBtn.setImageResource(R.drawable.ic_emoji_selector);
				}
			} else if (v == addMoreBtn) {
				editView.setVisibility(View.VISIBLE);
				sendAudioButton.setVisibility(View.GONE);
				emoji_action.setVisibility(View.GONE);
				emojiBtn.setImageResource(R.drawable.emoji);
				audioBtn.setImageResource(R.drawable.talk_detail_audio_btn);

				if (action_view.getVisibility() == View.VISIBLE) {
					// 更多布局已经显示
					if (more_actions.getVisibility() == View.VISIBLE) {
						showSoftKeyboard();
						try {
							Thread.sleep(200);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						setActionViewDisplay(1);
						more_actions.setVisibility(View.GONE);
					} else {
						// 更多布局未显示
						hideSoftKeyboard();
						more_actions.setVisibility(View.VISIBLE);
						gifViewPager.setVisibility(View.GONE);
						emoji_action.setVisibility(View.GONE);
					}
				} else {
					hideSoftKeyboard();
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					setActionViewDisplay(2);
					more_actions.setVisibility(View.VISIBLE);
					// showBottomView(1);
					// scrollToEnd();
				}
			}

		}

	};

	/**
	 * 显示emoji或者gif标点
	 *
	 * @param index
	 * @param file_type_name
	 */
	private void showIndexMark(int index, int type, String file_type_name) {
		if (index == 0 && type == 2) {
			initViewPageData(file_type_name);
		} else if (index == 0 && type == 1) {
			initEmojiViewPageData();
		}
		if (type == 2) {
			if (mAdapter == null)
				return;
		} else if (type == 1) {
			if (emojiAdapter == null) {
				return;
			}
		}
		int max = 0;
		if (type == 1) {
			max = emojiAdapter.getCount();
		} else {
			max = mAdapter.getCount();
		}
		indexGroup.removeAllViews();
		for (int i = 0; i < max; i++) {
			ImageView image = new ImageView(mContext);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			lp.leftMargin = 10;
			lp.rightMargin = 10;
			lp.topMargin = 5;
			lp.bottomMargin = 5;
			if (index == i) {
				image.setImageResource(R.drawable.point_selected);
			} else {
				image.setImageResource(R.drawable.point);
			}
			image.setLayoutParams(lp);
			indexGroup.addView(image);
		}

	}

	/**
	 * 初始化emoji事件
	 */
	private void initEmojiViewPageData() {
		emojiAdapter = new EmojiAdapter(mContext, new OnEmojiSelected() {
			@Override
			public void onEmojiSelected(Emoji emoji) {
				if (TextUtils.isEmpty(emoji.text)) {
					return;
				}

				int index = sendEdit.getSelectionStart();
				String text = sendEdit.getText().toString();
				String startString = text.substring(0, index);
				String endString = text.substring(index, text.length());
				String emojiText = "[" + emoji.text + "] ";

				sendEdit.setFocusable(true);
				sendEdit.setFocusableInTouchMode(true);
				sendEdit.requestFocus();
				sendEdit.setText(startString + emojiText + endString);
				sendEdit.setSelection(index + emojiText.length());
			}

			@Override
			public void onEmojiDeleted(Emoji emoji) {
				QyxEmoji.deleteEmoji(sendEdit, emoji.text);
			}
		});
		gifViewPager.setAdapter(emojiAdapter);
		initViewPageLisenter(1, "");
	}

	/**
	 * 初始化viewpage数据
	 *
	 * @param file_type_name
	 *            显示表情的所在文件夹的目录
	 */
	private void initViewPageData(final String file_type_name) {
		mAdapter = new GifAdapter(mContext, file_type_name,
				new OnBuildInViewGifSelected() {

					@Override
					public void onGifSelected(ViewGifCover mGif) {
						if (mGif.gifName.equals("loac_add")) {
							Intent intent = new Intent(mContext,
									StickerActivity.class);
							mContext.startActivity(intent);
						} else {
							if (mISendGifListener != null) {
								mISendGifListener.onSendGif(mGif,
										getGifName(mGif.gifName));
							}
						}

					}
				});
		gifViewPager.setAdapter(mAdapter);
		initViewPageLisenter(2, file_type_name);
	}

	/**
	 * 发送gif图片时,png图片名称转换为gif图片名称
	 *
	 * @param pngName
	 *            png图片名称
	 * @return gif图片名称
	 */
	private String getGifName(String pngName) {
		try {
			String str[] = pngName.split("_");
			String gif_name = str[0] + "_" + str[1];
			String name = gif_name + ".gif";
			return name;
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 注册ViewPage滑动事件
	 *
	 * @param type
	 *            1：emoji2：gif
	 * @param file_type_name
	 *            1：“”2：gif类型名称
	 */
	private void initViewPageLisenter(final int type,
			final String file_type_name) {
		gifViewPager.setMyDirectListener(new MyDirectListener() {

			@Override
			public void getsliderLister(final int direct) {
				new Handler().postDelayed(new Runnable() {
					public void run() {
						if (direct == 0) {
							showPreviousGif();
						} else {
							showLastGif();
						}
					}
				}, 50);
			}
		});
		gifViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int index) {
				showIndexMark(index, type, file_type_name);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				/** 设置viewpage滑动到最后一页和第一页的时切换其他类型Gif表情 **/
				// switch (arg0) {
				// case ViewPager.SCROLL_STATE_DRAGGING:
				// flag = false;
				// break;
				// case ViewPager.SCROLL_STATE_SETTLING:
				// flag = true;
				// break;
				// case ViewPager.SCROLL_STATE_IDLE:
				// if (gifViewPager.getCurrentItem() ==
				// gifViewPager.getAdapter()
				// .getCount() - 1 && !flag) {
				// showLastGif();
				// } else if (gifViewPager.getCurrentItem() == 0 && !flag) {
				// showPreviousGif();
				// }
				// flag = true;
				// break;
				// }
			}
		});
	}

	/**
	 * 显示下一个GifViewPage
	 */
	private void showLastGif() {
		if (selectedCheckEmoji != null && arrayList != null
				&& arrayList.size() > 0) {
			for (int i = 0, size = arrayList.size(); i < size; i++) {
				if (selectedCheckEmoji == arrayList.get(i)
						&& i < arrayList.size() - 1) {
					// 显示下一个GifViewPage
					int lastIndex = ++i;
					if (lastIndex >= arrayList.size()) {
						return;
					}
					/** 选中第一个item **/
					showIndexMark(0, 2, arrayList.get(lastIndex).resourceName);
					/** 设置当前选中的gif类型 **/
					selectedCheckEmoji = arrayList.get(lastIndex);
					/** 修改选中的表情背景 **/
					mBottomEmojiAdapter.setSelectedItem(arrayList
							.get(lastIndex).id);

					listView.scrollToPosition(lastIndex);
					break;
				}
			}
		}
	}

	/**
	 * 显示上个gifViewPage(默认选中上一个gif表情的最后一个item)
	 */
	private void showPreviousGif() {
		if (selectedCheckEmoji != null && arrayList != null
				&& arrayList.size() > 0) {
			for (int i = 0, size = arrayList.size(); i < size; i++) {
				if (selectedCheckEmoji == arrayList.get(i) && i != 0) {
					// 显示上一个GifViewPage
					int previousIndex = --i;
					if (previousIndex >= arrayList.size() || previousIndex < 0) {
						return;
					}
					int type = 0;
					if (previousIndex == 0) {
						// 第一页 显示emoji表情
						type = 1;
					} else {
						type = 2;
					}

					/** 选中最后一个item **/
					showIndexMark(0, type,
							arrayList.get(previousIndex).resourceName);
					/** 选中最后一个item **/
					if (gifViewPager != null) {
						int count = 0;
						if (previousIndex == 0) {
							// 第一页 显示emoji表情
							count = emojiAdapter.getCount() - 1;
						} else {
							count = mAdapter.getCount() - 1;
						}
						gifViewPager.setCurrentItem(count);
					}
					/** 设置当前选中的gif类型 **/
					selectedCheckEmoji = arrayList.get(previousIndex);
					/** 修改选中的表情背景 **/
					mBottomEmojiAdapter.setSelectedItem(arrayList
							.get(previousIndex).id);
					listView.scrollToPosition(previousIndex);
					break;
				}
			}
		}
	}

	/**
	 * 初始化更多数据
	 */
	public void initMoreAdapter(ArrayList<MoreEntity> _ArrayList,
			IMoreOnClickListener mIMoreOnClickListener) {
		mPanelMoreManager.initMoreAdapter(_ArrayList, mIMoreOnClickListener);
	}

	/**
	 * 设置底部view显示隐藏状态
	 *
	 * @param type
	 */
	private void setActionViewDisplay(int type) {
		if (action_view != null) {
			if (type == 1) {
				action_view.setVisibility(View.GONE);
				more_actions.setVisibility(View.GONE);
				emoji_action.setVisibility(View.GONE);
				emojiBtn.setImageResource(R.drawable.emoji);
			} else {
				action_view.setVisibility(View.VISIBLE);
			}
		}
	}

	private void showSoftKeyboard() {
		((Activity) mContext).getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

		inputManager
				.showSoftInput(sendEdit, InputMethodManager.HIDE_NOT_ALWAYS);
	}

	private void hideSoftKeyboard() {
		((Activity) mContext).getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

		if (inputManager.isActive()) {
			inputManager.hideSoftInputFromWindow(sendEdit.getWindowToken(), 0);
		}
	}

	/**
	 * 控制软键盘高度
	 */
	private ResizeLayout.OnResizeListener resizeListener = new ResizeLayout.OnResizeListener() {

		@Override
		public void OnResize(int w, int h, int oldw, int oldh) {
			if (oldw != 0 && oldh != 0) {
				if (h < oldh) {
					keyboardHeight = oldh - h;
					keyboardHeight = Math.max(dip2px(mContext, 260),
							keyboardHeight);
					IMApplication.config.setKeyBoardHeight(keyboardHeight);
					setFaceActionViewHeight();
				}
			}
		}
	};

	/**
	 * 设置面板高度
	 *
	 */
	private void setFaceActionViewHeight() {
		LayoutParams faceParams = action_view.getLayoutParams();
		faceParams.height = keyboardHeight;
		action_view.setLayoutParams(faceParams);
	}

	/**
	 * 把dip值转换成px值
	 */
	private int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public void hideFacePanel() {

	}

	/**
	 * 监听录音返回
	 *
	 * @param _SendAudioListener
	 */
	public void onSendAudioListener(PanelManagerInterface.ISendAudioListener _SendAudioListener) {
		mSendAudioListener = _SendAudioListener;
	}

	/**
	 * 发送按钮监听
	 *
	 * @param _SendTextListener
	 */
	public void onSendTextListener(PanelManagerInterface.ISendTextListener _SendTextListener) {
		mSendTextListener = _SendTextListener;
	}

	/**
	 * 发送gif监听
	 *
	 * @param _SendGifListener
	 */
	public void onSendGifListener(PanelManagerInterface.ISendGifListener _SendGifListener) {
		mISendGifListener = _SendGifListener;
	}

	/**
	 * 设置不显示面板
	 *
	 * @param _HideFacePanel
	 */
	public void onSendHideFacePanel(PanelManagerInterface.ISendHideFacePanel _HideFacePanel) {
		_HideFacePanel.onHideFacePanel(new PanelManagerInterface.IHideFacePanel() {

			@Override
			public void hideFacePanel() {
				setActionViewDisplay(1);
			}
		});
	}

	/**
	 * 监听何时滚动到底部
	 *
	 * @param _IScrollToEnd
	 */
	public void onScorllToEnd(PanelManagerInterface.IScrollToEnd _IScrollToEnd) {
		mIScrollToEnd = _IScrollToEnd;
	}

	/**
	 * 特殊字符输入监听
	 *
	 * @param _IInputSpecialChar
	 */
	public void onInputSpecialChar(PanelManagerInterface.IInputSpecialChar _IInputSpecialChar) {
		mIInputSpecialChar = _IInputSpecialChar;
	}

	/**
	 * 公众号点击监听
	 *
	 * @param _PublicNumOnClick
	 */
	public void onPublicNumOnclick(PanelManagerInterface.IPublicNumOnClick _PublicNumOnClick) {
		mPanelPublicNumManager.setPublicOnclick(_PublicNumOnClick);
	}

	public int getPanelStatus() {
		if (action_view.getVisibility() == View.VISIBLE) {
			return 1;
		} else {
			return 0;
		}
	}

	/**
	 * 隐藏公众号View
	 */
	public void hidePublicNumView() {
		publicNumLayout.setVisibility(View.GONE);
		publicNumSoft.setVisibility(View.GONE);
		public_num_view.setVisibility(View.GONE);
		kayboadFrameLayout.setVisibility(View.VISIBLE);
	}

	/**
	 * 显示公众号View
	 */
	public void showPublicNumView() {
		publicNumLayout.setVisibility(View.VISIBLE);
		publicNumSoft.setVisibility(View.VISIBLE);
		public_num_view.setVisibility(View.VISIBLE);
	}

	/**
	 * 设置公众号数据
	 *
	 * @param arrayList
	 */
	public void setPublicNumData(ArrayList<PublicNumMenu> arrayList) {
		if (isShowPublicNumSoft) {
			mPanelPublicNumManager.setPublicNumMenu(arrayList);
		}
	}

	public CheckEmojiEntity getCheckEmojiEntity() {
		CheckEmojiEntity mCheckEmojiEntity = null;
		for (int i = 0, size = arrayList.size(); i < size; i++) {
			if (arrayList.get(i).isSelected) {
				mCheckEmojiEntity = arrayList.get(i);
				break;
			}
		}
		return mCheckEmojiEntity;
	}

	public void setCheckEmojiEntity(CheckEmojiEntity mCheckEmojiEntity) {
		if (mCheckEmojiEntity != null) {

			if (selectedCheckEmoji == mCheckEmojiEntity) {
				return;
			} else {
				selectedCheckEmoji = mCheckEmojiEntity;
			}
			mBottomEmojiAdapter.setSelectedItem(mCheckEmojiEntity.id);
			if (mCheckEmojiEntity.id == -1
					&& mCheckEmojiEntity.resourceId == -1
					&& TextUtils.isEmpty(mCheckEmojiEntity.resourceName)) {
				showIndexMark(0, 1, mCheckEmojiEntity.resourceName);
			} else {
				showIndexMark(0, 2, mCheckEmojiEntity.resourceName);
			}

		}
	}
}
